package cn.innosmart.aq.view.fragment;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.tutk.p2p.ConnectionEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.innosmart.aq.BuildConfig;
import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.DeviceGridViewAdapter;
import cn.innosmart.aq.adapter.HelpInfoAdapter;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.AlarmConditionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.BannerInfo;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.bean.TriggerBean;
import cn.innosmart.aq.bean.ValueConditionBean;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.camera.protocol.Camera;
import cn.innosmart.aq.customize.AlarmDialog;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.InputDialog;
import cn.innosmart.aq.customize.ListDialog;
import cn.innosmart.aq.customize.PrioritySetDialog;
import cn.innosmart.aq.customize.ValueSetDialog;
import cn.innosmart.aq.customize.raymenu.RayMenu;
import cn.innosmart.aq.manager.DeviceManager;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.manager.SystemManager;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.AddCameraActivity;
import cn.innosmart.aq.view.activity.BoxDetailActivity;
import cn.innosmart.aq.view.activity.CameraSetActivity;
import cn.innosmart.aq.view.activity.DeviceHistoryDataChartsActivity;
import cn.innosmart.aq.view.activity.HubSettingActivity;
import cn.innosmart.aq.view.activity.PushMessageSettingAcitivity;
import cn.innosmart.aq.view.activity.SmsPushMessageActivity;
import cn.innosmart.aq.view.activity.TelPushMessageActivity;

/**
 * Created by David on 2015/7/23.
 */
public class BoxDetailCurrentFragment extends BaseFragment implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener {
    /**
     * , R.drawable.armenu_video_over
     */
    private static final int[] ITEM_DRAWABLES = {
            R.drawable.armenu_screen_shot,
            R.drawable.armenu_hear_over,
            R.drawable.armenu_voice,
            R.drawable.btn_fullscreen_over,
            R.drawable.armenu_exit};

    private final int LOADINGSTART = 0;
    private final int LOADINGSUCCESS = 1;
    private final int LOADINGFAIL = 2;
    private final int PHCHANGE = 3;
    private final int TEMPCHANGE = 4;
    private final int DATACHANGE = 5;

    private final int SHOW_BANNER = 6;
    private final int HIDE_BANNER = 7;

    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private View view;
    private GridView gvDevice;
    private DeviceGridViewAdapter deviceGridViewAdapter;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOADINGSTART:
                    //显示加载对话框
                    showLoadingDialog(getActivity());
                    break;
                case LOADINGSUCCESS:
                    //加载成功
                    hideLoadingDialog();
                    break;
                case LOADINGFAIL:
                    //加载失败
                    hideLoadingDialog();
                    break;
                case PHCHANGE:

                    break;
                case DATACHANGE:
                    //刷新UI
                    deviceGridViewAdapter.notifyDataSetChanged();
                    break;

                case SHOW_BANNER:
                    view.findViewById(R.id.framelayout_banner).setVisibility(View.VISIBLE);
//                    sliderLayout.setVisibility(View.VISIBLE);
                    deviceGridViewAdapter.notifyDataSetChanged();
                    break;

                case HIDE_BANNER:
//                    sliderLayout.setVisibility(View.GONE);
                    view.findViewById(R.id.framelayout_banner).setVisibility(View.GONE);
                    deviceGridViewAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private AquariumBean aquariumBean;
    private ConnectionEntity connectionEntity;
    //图标点击事件监听器
    private View.OnClickListener mOnNormalIconClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object object = v.getTag();
            if (object instanceof DeviceBean) {
                //跳转到图表界面
                switchChartActivity((DeviceBean) object);
            } else if (object instanceof CameraBean) {

            } else {
            }
        }
    };

    private View.OnClickListener mOnValueClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object object = v.getTag();
            if (object instanceof DeviceBean) {
                //跳转到图表界面
                switchChartActivity((DeviceBean) object);
            }
        }
    };


    private View.OnClickListener mOnAlarmIconClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("View.getTag(1234)=" + v.getTag(R.string.alarmType));
//            Toast.makeText(getActivity(), "Alarm Recommendation", Toast.LENGTH_SHORT).show();
            AlarmDialog alarmDialog = new AlarmDialog(getActivity());
            String info = "";
            switch ((Integer) (v.getTag(R.string.alarmType))) {
                case 1: //low water level
                    info = getActivity().getString(R.string.advice_alam_waterlevel);
                    break;
                case 2: //high water level
                    info = getActivity().getString(R.string.advice_alam_waterlevel_high);
                    break;
                case 3: //low ph alarm
                    info = getActivity().getString(R.string.advice_alam_ph);
                    break;
                case 4: //high ph alarm
                    info = getActivity().getString(R.string.advice_alam_ph_high);
                    break;
                case 5: //low temperature
                    info = getActivity().getString(R.string.advice_alam_temperature);
                    break;
                case 6: //high temperature
                    info = getActivity().getString(R.string.advice_alam_temperature_high);
                    break;
                case 7: // device no report
                    info = getActivity().getString(R.string.advice_alam_device_no_report);
                    break;
                case 8: //low watt exception
                    info = getActivity().getString(R.string.advice_alam_low_watt);
                    break;
                case 9: //
                    info = getActivity().getString(R.string.advice_alam_online_offline);
                    break;
            }


            alarmDialog.setContent(info);
            alarmDialog.show();
        }
    };

    private SliderLayout sliderLayout;
    private ArrayList<BannerInfo> bannerInfoList = new ArrayList<>();
    private CameraBean openCamera;
    private BoxDetailActivity mActivity;

    //标签点击事件
    private View.OnClickListener mNameOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object object = v.getTag();
            if (object instanceof DeviceBean) {
                showModifyDevice((DeviceBean) object);
            } else if (object instanceof CameraBean) {
                CameraBean cameraBean = (CameraBean) object;
                Intent modifyCameraIntent = new Intent(getActivity(), AddCameraActivity.class);
                modifyCameraIntent.putExtra("flag", 2);
                modifyCameraIntent.putExtra("CamUid", cameraBean.getUid());
                startActivityForResult(modifyCameraIntent, 1);
            } else {
            }
        }
    };
    private CameraBean currentCamera;
    private boolean isListen = false;
    private boolean isSpeak = false;

    //控制按钮点击事件监听
    private View.OnClickListener mOnControlButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object object = v.getTag();

            if (object instanceof DeviceBean) {
                DeviceBean bean = (DeviceBean) object;
                if (((DeviceBean) object).getAddress().equals("AQGW")) {
                    showAQGWSettingDialog();
                    return;
                }
            }
            switch (v.getId()) {
                case R.id.rl_left:
                    //左侧按钮点击
                    if (object instanceof DeviceBean) {
                        //设备
                        DeviceBean deviceBean = (DeviceBean) object;
                        if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                            openSwitch(deviceBean);
                        } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                            controlFeeder(deviceBean);
                        }
                    } else if (object instanceof CameraBean) {
                        //打开摄像头
                        CameraBean cameraBean = (CameraBean) object;
                        if (cameraBean.getStatus() == com.tutk.IOTC.Camera.CONNECTION_STATE_CONNECTED) {
                            if (cameraBean.isShown()) {
                                hideCameraView(cameraBean);
                            } else {
                                showCameraView((CameraBean) object);
                            }
                        } else {
                            showToast("摄像头不在线");
                        }
                    } else {
                    }
                    break;
                case R.id.rl_right:
                    //右侧按钮点击
                    if (object instanceof DeviceBean) {
                        //设备
                        DeviceBean deviceBean = (DeviceBean) object;
                        if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                            closeSwitch(deviceBean);
                        } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                            controlFeeder(deviceBean);
                        }
                    } else if (object instanceof CameraBean) {
//                        CameraBean cameraBean = (CameraBean) object;
//                        if (currentCamera.getUid().equals(cameraBean.getUid())) {
//                            mActivity.setCurrentCamera(null);
//                            cameraBean.disConnect();
//                            view.findViewById(R.id.ll_banner).setVisibility(View.GONE);
//                            view.findViewById(R.id.ray_menu).setVisibility(View.GONE);
//                            view.findViewById(R.id.pb_loading).setVisibility(View.GONE);
//                            sliderLayout.startAutoCycle();
//                        }
                        //设置摄像头，仅在线，必须先点击查看
                        CameraBean cameraBean = (CameraBean) object;
                        if (cameraBean.getStatus() == com.tutk.IOTC.Camera.CONNECTION_STATE_CONNECTED) {
                            Intent cameraSetIntent = new Intent(getActivity(), CameraSetActivity.class);
                            cameraSetIntent.putExtra("CameraBean", cameraBean.getUid());
                            startActivityForResult(cameraSetIntent, 0);
                        } else {
                            showToast("摄像头不在线");
                        }
                    } else {
                    }
                    break;
                case R.id.config_button: {
                    System.out.println("OnClickListener config_button");
                    DeviceBean deviceBean = (DeviceBean) object;
                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                        System.out.println("deviceBean address:" + deviceBean.getAddress()); // zwave://e5a00bee/3/37/3/0

                        String slist[] = deviceBean.getAddress().split("\\/");
                        String wattDeviceBeanAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 50 + "/" + slist[5] + "/" + 2; // zwave://e5a00bee/3/50/3/2
                        DeviceBean wattDeviceBean = SystemConstant.deviceBeanHashMap.get(wattDeviceBeanAddress);

                        if (wattDeviceBean != null) {
                            showSwitchLowWattDialog(deviceBean, wattDeviceBean, true);
                        } else {
                            showSwitchLowWattDialog(deviceBean, wattDeviceBean, false);
                        }
                    }
                }
                break;
                case R.id.detech_bottom: {
                    //设置报警区间
                    DeviceBean deviceBean = (DeviceBean) object;
                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_PH) {
                        showPhValueSetDialog(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                        showTemperatureValueSetDialog(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                        controlFeeder(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                        showWaterAlertDialog(deviceBean);
                    }
                }
                break;
                case R.id.middle_button: {
                    //设置报警区间
                    DeviceBean deviceBean = (DeviceBean) object;
                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_PH) {
                        showPhValueSetDialog(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                        showTemperatureValueSetDialog(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER) {
                        controlFeeder(deviceBean);
                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                        showWaterAlertDialog(deviceBean);
                    }
                }
                break;
            }

        }
    };

    private void showMaintainModeStatus() {
        TextView tv = (TextView) (getActivity().findViewById(R.id.tv_maintain_status));
        tv.setVisibility(View.VISIBLE);

        if (this.aquariumBean.getMaintainMode() == 1) {
            AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f);
            AlphaAnimation fadeOut = new AlphaAnimation(0.0f, 1.0f);
            tv.startAnimation(fadeIn);
            tv.startAnimation(fadeOut);
            fadeIn.setDuration(1200);
            fadeIn.setFillAfter(true);
            fadeIn.setRepeatCount(Animation.INFINITE);
            fadeOut.setDuration(1200);
            fadeOut.setFillAfter(true);
            fadeOut.setRepeatCount(Animation.INFINITE);
            fadeIn.setStartOffset(4200 + fadeIn.getStartOffset());
        } else {
            tv.setVisibility(View.INVISIBLE);
        }
    }

    private void hideMaintainModeStatus() {
        TextView tv = (TextView) (getActivity().findViewById(R.id.tv_maintain_status));
        tv.setVisibility(View.INVISIBLE);
        tv.clearAnimation();
    }

    //设置水位报警的对话框
    private void showWaterAlertDialog(final DeviceBean deviceBean) {
        final ValueSetDialog waterAlertDialog = new ValueSetDialog(getActivity());
        waterAlertDialog.findViewById(R.id.iv_help).setVisibility(View.GONE);
        final TextView tvPriority = (TextView) waterAlertDialog.findViewById(R.id.tv_priority);
        tvPriority.setTag(3);
        final CheckBox cbEnable = (CheckBox) waterAlertDialog.findViewById(R.id.cb_waterlever_check);
        //查找之前设置的报警条件
        if (DeviceConstant.alarmConditionBeanHashMap != null) {
            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
            if (alarmConditionBean != null) {
                if (alarmConditionBean.getEnable() == 1) {
                    cbEnable.setChecked(true);
                } else {
                    cbEnable.setChecked(false);
                }
                RuleBean deleteRule = null;
                for (Object object : SystemConstant.conditionRuleList) {
                    RuleBean ruleBean = (RuleBean) object;
                    if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                        deleteRule = ruleBean;
                    }
                }
                tvPriority.setTag(deleteRule.pns_priority);
            } else {
                cbEnable.setChecked(false);
            }
        } else {
            cbEnable.setChecked(false);
        }
        tvPriority.setText(priorityStrIds[(int) tvPriority.getTag()]);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriorityWindow(tvPriority);
            }
        });
        waterAlertDialog.setWater();
        waterAlertDialog.setTitle(mActivity.getString(R.string.alarm_set));
        waterAlertDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbEnable.isChecked()) {
                    if (DeviceConstant.alarmConditionBeanHashMap != null) {
                        AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                        if (alarmConditionBean == null) {
                            addWaterRule(cbEnable, deviceBean, tvPriority);
                        } else {
                            RuleBean ruleBean = null;
                            RuleBean modifyRule = null;
                            for (Object object : SystemConstant.conditionRuleList) {
                                ruleBean = (RuleBean) object;
                                if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                                    modifyRule = ruleBean;
                                }
                            }
                            modifyWaterRule(cbEnable, modifyRule.getId(), deviceBean, tvPriority);
                        }
                    }
                } else {
                    if (DeviceConstant.alarmConditionBeanHashMap != null) {
                        AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                        if (alarmConditionBean != null) {
                            removeWaterRule(deviceBean);
                        }
                    }
                }
                waterAlertDialog.dismiss();
            }
        });
        waterAlertDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                waterAlertDialog.dismiss();
            }
        });
        waterAlertDialog.show();
    }

    /**
     * 修改水位报警的规则条件
     *
     * @param cbEnable
     * @param id
     * @param deviceBean
     * @param tvPriority
     */
    private void modifyWaterRule(final CheckBox cbEnable, final String id, final DeviceBean deviceBean, TextView tvPriority) {
        final RuleBean ruleBean = new RuleBean();
        if (SystemConstant.conditionRuleList == null)
            SystemConstant.conditionRuleList = new ArrayList<>();
        for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
            RuleBean ruleBeans = SystemConstant.conditionRuleList.get(i);
            ArrayList<CommandBean> commandBeans = new ArrayList<CommandBean>();
            HashMap<String, TriggerBean> actiongs = new HashMap<String, TriggerBean>();
            if (ruleBeans.getId().equals(id)) {
                ruleBean.setEnabled(ruleBeans.getEnabled());
                ruleBean.setPns(ruleBeans.getPns());
                ruleBean.setRepeat_type(ruleBeans.getRepeat_type());
                commandBeans.addAll(ruleBeans.getCommands());
                ruleBean.setCommands(commandBeans);
                ruleBean.setIcon_data(ruleBeans.getIcon_data() == null ? null : new String(ruleBeans.getIcon_data()));
                ruleBean.setId(ruleBeans.getId() == null ? null : new String(ruleBeans.getId()));
                ruleBean.setPlace(ruleBeans.getPlace() == null ? null : new String(ruleBeans.getPlace()));
                ruleBean.setWeekdays(ruleBeans.getWeekdays());
                actiongs.putAll(ruleBeans.getTriggers());
                ruleBean.setTriggers(actiongs);
                ruleBean.setTitle(ruleBeans.getTitle() == null ? null : new String(ruleBeans.getTitle()));
                ruleBean.setUserTag(ruleBeans.getUserTag() == null ? null : new String(ruleBeans.getUserTag()));
                break;
            }
        }
        ruleBean.pns_priority = (int) tvPriority.getTag();
        if (cbEnable.isChecked())
            ruleBean.setEnabled(1);
        else
            ruleBean.setEnabled(0);
        RuleManager.getInstance().Update(connectionEntity, ruleBean.toParams().toString(), new RuleManager.UpdateCallBack() {
            @Override
            public void onUpdateResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
                        RuleBean oldruleBean = SystemConstant.conditionRuleList.get(i);
                        if (id.equals(oldruleBean.getId())) {
                            SystemConstant.conditionRuleList.remove(i);
                            SystemConstant.conditionRuleList.add(ruleBean);
                            DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).setEnable(cbEnable.isChecked() ? 1 : 0);
                            if (deviceBean.getSensorvalue() < DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getAboveValue() || deviceBean.getSensorvalue() > DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getBelowValue()) {
                                deviceBean.setAlarm(true);
                            } else {
                                deviceBean.setAlarm(false);
                            }
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                }
            }
        });
    }

    /**
     * 删除水位规则
     *
     * @param deviceBean
     */
    private void removeWaterRule(final DeviceBean deviceBean) {
        RuleBean deleteRule = null;
        //根据Device设备找到 相应规则条件
        for (Object object : SystemConstant.conditionRuleList) {
            RuleBean ruleBean = (RuleBean) object;
            if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                deleteRule = ruleBean;
            }
        }
        final RuleBean finalDeleteRule = deleteRule;
        //发送删除规则指令
        RuleManager.getInstance().Remove(connectionEntity, finalDeleteRule.toDeleteParams(), new RuleManager.RemoveCallBack() {
            @Override
            public void onRemoveResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    DeviceConstant.alarmConditionBeanHashMap.remove(deviceBean.getAddress());
                    //更新UI
                    mHandler.sendEmptyMessage(DATACHANGE);
                }
            }
        });
    }

    private void showAQGWSettingDialog() {
        final ValueSetDialog aqgwSettingDialog = new ValueSetDialog(getActivity());
        aqgwSettingDialog.findViewById(R.id.iv_help).setVisibility(View.GONE);

        final TextView tvPriority = (TextView) aqgwSettingDialog.findViewById(R.id.tv_priority);
        int pns_priority = SystemConstant.heart_pns_priority - 3;
        if (pns_priority <= 0)
            pns_priority = 3;
        tvPriority.setTag(pns_priority);

        final CheckBox cbEnable = (CheckBox) aqgwSettingDialog.findViewById(R.id.cb_offline_check);
        aqgwSettingDialog.findViewById(R.id.ll_gw_setting).setVisibility(View.VISIBLE);
        System.out.println("heart_enable before change:" + SystemConstant.heart_enable);

        if (SystemConstant.heart_enable == 0) {
            cbEnable.setChecked(false);
        } else if (SystemConstant.heart_enable == 1) {
            cbEnable.setChecked(true);
        } else {
            cbEnable.setChecked(false);
        }

        tvPriority.setText(priorityStrIds[(int) tvPriority.getTag()]);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbEnable.setChecked(true);
                showPriorityWindow(tvPriority);
            }
        });
        aqgwSettingDialog.setTitle(mActivity.getString(R.string.alarm_set));
        aqgwSettingDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject jParams = new JSONObject();
                JSONObject jUserdata = new JSONObject();

                if (cbEnable.isChecked()) {
                    System.out.println("cbEnable.isChecked()");
                    SystemConstant.heart_enable = 1;
                    int heart_pns_priority = (Integer) (tvPriority.getTag()) + 3;
                    SystemConstant.heart_pns_priority = heart_pns_priority;
                } else {
                    System.out.println("cbEnable.isChecked() false");
                    SystemConstant.heart_enable = 0;
                    int heart_pns_priority = (Integer) (tvPriority.getTag()) + 3;
                    SystemConstant.heart_pns_priority = heart_pns_priority;
                }

                System.out.println("heart_enable:" + SystemConstant.heart_enable);
                try {
                    jUserdata.put("heart_enable", SystemConstant.heart_enable);
                    jUserdata.put("heart_pns_priority", SystemConstant.heart_pns_priority);
                    jParams.put("userdata", jUserdata);
                    SystemManager.getInstance().SetUserData(connectionEntity, jParams, 100);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                aqgwSettingDialog.dismiss();
            }
        });
        aqgwSettingDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aqgwSettingDialog.dismiss();
            }
        });
        aqgwSettingDialog.show();
    }

    //设置Switch Low Watt的对话框
    private void showSwitchLowWattDialog(final DeviceBean parentDeviceBean, final DeviceBean wattDeviceBean, final boolean hasWattDevice) {
        final ValueSetDialog lowWattAlertDialog = new ValueSetDialog(getActivity());
        final TextView tvPriority = (TextView) lowWattAlertDialog.findViewById(R.id.tv_priority);
        tvPriority.setTag(3);
        final CheckBox cbEnable = (CheckBox) lowWattAlertDialog.findViewById(R.id.cb_lowWatt_check);
        final CheckBox cbAutoControlEnable = (CheckBox) lowWattAlertDialog.findViewById(R.id.cb_auto_open_check);

        if (parentDeviceBean.getRebootValue() == 0) {
            cbAutoControlEnable.setChecked(false);
        } else if (parentDeviceBean.getRebootValue() == 255) {
            cbAutoControlEnable.setChecked(true);
        } else {
            cbAutoControlEnable.setChecked(false);
        }
        final boolean lastAutoControl = cbAutoControlEnable.isChecked();

        //查找之前设置的报警条件
        if (DeviceConstant.alarmConditionBeanHashMap != null && hasWattDevice) {
            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
            if (alarmConditionBean != null) {
//                System.out.println("existed alarm condition bean for watt exception");
                if (alarmConditionBean.getEnable() == 1) {
                    cbEnable.setChecked(true);
                } else {
                    cbEnable.setChecked(false);
                }
                RuleBean deleteRule = null;
                for (Object object : SystemConstant.conditionRuleList) {
                    RuleBean ruleBean = (RuleBean) object;
                    if (parentDeviceBean.getAddress().equals(ruleBean.getUserTag())) {
                        deleteRule = ruleBean;
                    }
                }
                tvPriority.setTag(deleteRule.pns_priority);
            } else {
                cbEnable.setChecked(false);
            }
        } else {
            cbEnable.setChecked(false);
        }

        tvPriority.setText(priorityStrIds[(int) tvPriority.getTag()]);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriorityWindow(tvPriority);
            }
        });
        lowWattAlertDialog.setWattException();

        if (hasWattDevice == true) {
            lowWattAlertDialog.findViewById(R.id.cb_lowWatt_check).setVisibility(View.VISIBLE);
        } else {
            lowWattAlertDialog.findViewById(R.id.tv_watt_warning_text).setVisibility(View.GONE);
        }

        lowWattAlertDialog.setTitle(mActivity.getString(R.string.alarm_set));
        lowWattAlertDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (lastAutoControl != cbAutoControlEnable.isChecked()) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("reboot_value", cbAutoControlEnable.isChecked() ? 255 : 0);
                        jsonObject.put("address", parentDeviceBean.getAddress());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    DeviceManager.getInstance().Update(connectionEntity, jsonObject.toString(), new DeviceManager.UpdateCallBack() {
                        @Override
                        public void onUpdateResponseCallBack(int ret) {
                            if (ret == 0) {
                                parentDeviceBean.setRebootValue(cbAutoControlEnable.isChecked() ? 255 : 0);
                            }
                        }
                    });
                }

                if (hasWattDevice) {
                    if (cbEnable.isChecked()) {
                        System.out.println("cbEnable.isChecked()");
                        if (DeviceConstant.alarmConditionBeanHashMap != null) {
                            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
                            if (alarmConditionBean == null) {
                                addWattExceptionRule(cbEnable, parentDeviceBean, wattDeviceBean, tvPriority);
                            } else {
                                //edit rule
                                RuleBean ruleBean = null;
                                RuleBean modifyRule = null;
                                for (Object object : SystemConstant.conditionRuleList) {
                                    ruleBean = (RuleBean) object;
                                    if (ruleBean.getTriggers().containsKey(wattDeviceBean.getAddress())) {
                                        modifyRule = ruleBean;
                                    }
                                }
                                modifyLowWattRule(cbEnable, modifyRule.getId(), wattDeviceBean, tvPriority);
                            }
                        }
                    } else {
                        System.out.println("cbEnable.isChecked() false");

                        if (DeviceConstant.alarmConditionBeanHashMap != null) {
                            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
                            if (alarmConditionBean != null) {
                                System.out.println("alarmConditionBean: " + alarmConditionBean.getEnable());
                                removeLowWattRule(parentDeviceBean, wattDeviceBean);
                            }
                        }
                    }
                }


                lowWattAlertDialog.dismiss();
            }
        });
        lowWattAlertDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lowWattAlertDialog.dismiss();
            }
        });
        lowWattAlertDialog.show();
    }

    private void addWattExceptionRule(final CheckBox cbEnable, final DeviceBean parentDeviceBean, final DeviceBean wattDeviceBean, TextView tvPriority) {
        System.out.println("addWattExceptionRule");

        final RuleBean ruleBean = new RuleBean();
        ruleBean.setEnabled(1);
        if (cbEnable.isChecked()) {
            ruleBean.setPns("pns");
        }
        ruleBean.setTitle(parentDeviceBean.getName() + "(" + mActivity.getString(R.string.lowWatt_alarm_name) + ")");
        ruleBean.setIcon_data("icon_data");
        ruleBean.setIcon_type("icon_type");
        ruleBean.setPlace(aquariumBean.getId());
        ruleBean.pns_priority = (int) tvPriority.getTag();
        ruleBean.setRepeat_type(0);
        ruleBean.setWeekdays(127);
        ruleBean.setUserTag(parentDeviceBean.getAddress());

        HashMap<String, TriggerBean> triggerBeanHashMap = new HashMap<String, TriggerBean>();


        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setAddress(wattDeviceBean.getAddress());
        ArrayList<ValueConditionBean> valueConditionBeans = new ArrayList<ValueConditionBean>();
        ValueConditionBean valueConditionBean = new ValueConditionBean();
        valueConditionBean.setField("sensorvalue");
        valueConditionBean.setDuaration(5);
        valueConditionBean.setThreshold(10);
        valueConditionBean.setOp("<");

        ValueConditionBean valueConditionBean3 = new ValueConditionBean();
        valueConditionBean3.setField("sensorvalue");
        valueConditionBean3.setDuaration(5);
        valueConditionBean3.setThreshold(-1);
        valueConditionBean3.setOp(">");

        valueConditionBeans.add(valueConditionBean);
        valueConditionBeans.add(valueConditionBean3);

        triggerBean.setValueConditionBeans(valueConditionBeans);
        triggerBeanHashMap.put(wattDeviceBean.getAddress(), triggerBean);

        TriggerBean triggerBean2 = new TriggerBean();
        triggerBean2.setAddress(parentDeviceBean.getAddress());
        ArrayList<ValueConditionBean> valueConditionBeans2 = new ArrayList<ValueConditionBean>();
        ValueConditionBean valueConditionBean2 = new ValueConditionBean();
        valueConditionBean2.setField("sensorvalue");
        valueConditionBean2.setDuaration(0);
        valueConditionBean2.setThreshold(255);
        valueConditionBean2.setOp("=");
        valueConditionBeans2.add(valueConditionBean2);
        triggerBean2.setValueConditionBeans(valueConditionBeans2);
        triggerBeanHashMap.put(parentDeviceBean.getAddress(), triggerBean2);

        ruleBean.setTriggers(triggerBeanHashMap);
        ArrayList<CommandBean> commands = new ArrayList<CommandBean>();
        ruleBean.setCommands(commands);
        HashMap<Integer, JSONArray> timeLine = new HashMap<Integer, JSONArray>();
        for (int i = 0; i < 7; i++) {
            JSONArray jsonChild = new JSONArray();
            jsonChild.put(i * 24 * 60);
            jsonChild.put((i + 1) * 24 * 60 - 1);
            timeLine.put(i, jsonChild);
        }
        ruleBean.setTimeLine(timeLine);
        //发送添加规则的指令
        RuleManager.getInstance().Add(connectionEntity, ruleBean.toParams().toString(), new RuleManager.AddCallBack() {
            @Override
            public void onAddResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    ruleBean.setId(ruleid);
                    if (SystemConstant.conditionRuleList == null)
                        SystemConstant.conditionRuleList = new ArrayList<>();
                    SystemConstant.conditionRuleList.add(ruleBean);
                    AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
                    if (alarmConditionBean == null) {
                        alarmConditionBean = new AlarmConditionBean();
                        alarmConditionBean.setEnable(1);
                        alarmConditionBean.setId(wattDeviceBean.getDeviceid());
                    } else {
                    }
                    DeviceConstant.alarmConditionBeanHashMap.put(wattDeviceBean.getAddress(), alarmConditionBean);
                    mHandler.sendEmptyMessage(DATACHANGE);
                    hideLoadingDialog();
                }
            }
        });
    }

    private void modifyLowWattRule(final CheckBox cbEnable, final String id, final DeviceBean deviceBean, TextView tvPriority) {
        final RuleBean ruleBean = new RuleBean();
        if (SystemConstant.conditionRuleList == null)
            SystemConstant.conditionRuleList = new ArrayList<>();
        for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
            RuleBean ruleBeans = SystemConstant.conditionRuleList.get(i);
            ArrayList<CommandBean> commandBeans = new ArrayList<CommandBean>();
            HashMap<String, TriggerBean> actiongs = new HashMap<String, TriggerBean>();
            if (ruleBeans.getId().equals(id)) {
                ruleBean.setEnabled(ruleBeans.getEnabled());
                ruleBean.setPns(ruleBeans.getPns());
                ruleBean.setRepeat_type(ruleBeans.getRepeat_type());
                commandBeans.addAll(ruleBeans.getCommands());
                ruleBean.setCommands(commandBeans);
                ruleBean.setIcon_data(ruleBeans.getIcon_data() == null ? null : new String(ruleBeans.getIcon_data()));
                ruleBean.setId(ruleBeans.getId() == null ? null : new String(ruleBeans.getId()));
                ruleBean.setPlace(ruleBeans.getPlace() == null ? null : new String(ruleBeans.getPlace()));
                ruleBean.setWeekdays(ruleBeans.getWeekdays());
                actiongs.putAll(ruleBeans.getTriggers());
                ruleBean.setTriggers(actiongs);
                ruleBean.setTitle(ruleBeans.getTitle() == null ? null : new String(ruleBeans.getTitle()));
                ruleBean.setUserTag(ruleBeans.getUserTag() == null ? null : new String(ruleBeans.getUserTag()));
                break;
            }
        }
        ruleBean.pns_priority = (int) tvPriority.getTag();
        if (cbEnable.isChecked())
            ruleBean.setEnabled(1);
        else
            ruleBean.setEnabled(0);
        RuleManager.getInstance().Update(connectionEntity, ruleBean.toParams().toString(), new RuleManager.UpdateCallBack() {
            @Override
            public void onUpdateResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
                        RuleBean oldruleBean = SystemConstant.conditionRuleList.get(i);
                        if (id.equals(oldruleBean.getId())) {
                            SystemConstant.conditionRuleList.remove(i);
                            SystemConstant.conditionRuleList.add(ruleBean);
                            DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).setEnable(cbEnable.isChecked() ? 1 : 0);
                            if (deviceBean.getSensorvalue() < DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getAboveValue() || deviceBean.getSensorvalue() > DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getBelowValue()) {
                                deviceBean.setAlarm(true);
                            } else {
                                deviceBean.setAlarm(false);
                            }
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                }
            }
        });
    }

    private void removeLowWattRule(final DeviceBean parentDeviceBean, final DeviceBean wattDeviceBean) {
        RuleBean deleteRule = null;
        //根据Device设备找到 相应规则条件
        int ruleBeanIndex = 0;
        for (Object object : SystemConstant.conditionRuleList) {
            RuleBean ruleBean = (RuleBean) object;
            if (ruleBean.getTriggers().containsKey(wattDeviceBean.getAddress())) {
                System.out.println("to remove ruleBean: " + ruleBean);
                deleteRule = ruleBean;
                break;
            }
            ruleBeanIndex++;
        }
        final RuleBean finalDeleteRule = deleteRule;
        final int finalRuleBeanIndex = ruleBeanIndex;
        //发送删除规则指令
        RuleManager.getInstance().Remove(connectionEntity, finalDeleteRule.toDeleteParams(), new RuleManager.RemoveCallBack() {
            @Override
            public void onRemoveResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    DeviceConstant.alarmConditionBeanHashMap.remove(wattDeviceBean.getAddress());
                    SystemConstant.conditionRuleList.remove(finalRuleBeanIndex);
                    //更新UI
                    mHandler.sendEmptyMessage(DATACHANGE);
                }
            }
        });
    }

    //播放摄像头界面
    private void showCameraView(CameraBean object) {
        if (currentCamera != null) {
            hideCameraView(currentCamera);
        }
        currentCamera = object;
        mActivity.setCurrentCamera(object);
        sliderLayout.stopAutoCycle();
        final ProgressBar pbLoading = (ProgressBar) view.findViewById(R.id.pb_loading);
        //设置卫星菜单
        final RayMenu rayMenu = (RayMenu) view.findViewById(R.id.ray_menu);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pbLoading.setVisibility(View.VISIBLE);
                view.findViewById(R.id.ll_banner).setVisibility(View.VISIBLE);
            }
        });
        CameraBean cameraBean = object;
        FragmentManager fm = getActivity().getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        if (cameraBean.getView() != null) {
            tx.replace(R.id.ll_banner, cameraBean.getView(), "Camera");
            tx.commit();
        }
        cameraBean.setShown(true);
        rayMenu.resetItemStatus(ITEM_DRAWABLES);
        init(cameraBean, rayMenu);
        pbLoading.setVisibility(View.GONE);
        rayMenu.setVisibility(View.VISIBLE);
        deviceGridViewAdapter.notifyDataSetChanged();
    }

    /**
     * 打开插座
     *
     * @param deviceBean
     */
    private void openSwitch(final DeviceBean deviceBean) {
        JSONObject jsonParams = new JSONObject();
        mHandler.sendEmptyMessage(LOADINGSTART);
        try {
            jsonParams.put("address", deviceBean.getAddress());
            jsonParams.put("value", 255);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //发送控制指令
        DeviceManager.getInstance().Control(connectionEntity, jsonParams.toString(), new DeviceManager.ControlCallBack() {
            @Override
            public void onControlResponseCallBack(int ret) {
                if (ret == 0) {
                    deviceBean.setSensorvalue(255);
                    mHandler.sendEmptyMessage(LOADINGSUCCESS);
                } else {
                    mHandler.sendEmptyMessage(LOADINGFAIL);
                }
            }
        });
    }

    /**
     * 关闭插座
     *
     * @param deviceBean
     */
    private void closeSwitch(final DeviceBean deviceBean) {
        JSONObject jsonParams = new JSONObject();
        mHandler.sendEmptyMessage(LOADINGSTART);
        try {
            jsonParams.put("address", deviceBean.getAddress());
            jsonParams.put("value", 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //发送控制指令
        DeviceManager.getInstance().Control(connectionEntity, jsonParams.toString(), new DeviceManager.ControlCallBack() {
            @Override
            public void onControlResponseCallBack(int ret) {
                if (ret == 0) {
                    deviceBean.setSensorvalue(0);
                    mHandler.sendEmptyMessage(LOADINGSUCCESS);
                } else {
                    mHandler.sendEmptyMessage(LOADINGFAIL);
                }
            }
        });
    }

    /**
     * 保存截图
     */
    private void saveSnapshot() {
        FileOutputStream out = null;
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getActivity().getPackageName());
            if (!file.mkdirs()) {
                Log.d("kukuri", "dir not created.");
            }
            out = new FileOutputStream(new File(file, System.currentTimeMillis() + ".jpg"));
            currentCamera.getSnapShot().compress(Bitmap.CompressFormat.JPEG, 100, out);
            mActivity.showToast(getString(R.string.screenshot_success));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mActivity.showToast(mActivity.getString(R.string.screenshot_failed));
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化摄像头
     * 卫星菜单初始化及点击事件监听
     *
     * @param cameraBean
     * @param rayMenu
     */
    public void init(final CameraBean cameraBean, final RayMenu rayMenu) {
        final int itemCount = ITEM_DRAWABLES.length;
        if (rayMenu.getChildCounts() == 0) {
            for (int i = 0; i < itemCount; i++) {
                ImageView item = new ImageView(getActivity());
                item.setImageResource(ITEM_DRAWABLES[i]);
                final int position = i;


                WindowManager w = getActivity().getWindowManager();
                Display d = w.getDefaultDisplay();
                DisplayMetrics metrics = new DisplayMetrics();
                d.getMetrics(metrics);
// since SDK_INT = 1;
                int widthPixels = metrics.widthPixels;
                int heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
                if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
                    try {
                        widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
                        heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
                    } catch (Exception ignored) {
                    }
// includes window decorations (statusbar bar/menu bar)
                if (Build.VERSION.SDK_INT >= 17)
                    try {
                        Point realSize = new Point();
                        Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
                        widthPixels = realSize.x;
                        heightPixels = realSize.y;
                    } catch (Exception ignored) {
                    }

                item.setScaleX((float) (widthPixels / 1080.0));
                item.setScaleY((float) (heightPixels / 1920.0));

                rayMenu.addItem(item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (position) {
                            case 0:
                                //截图
                                saveSnapshot();
                                break;
                            case 1:
                                ////摄像头监听
                                rayMenu.resetItemStatus(ITEM_DRAWABLES);
                                isListen = !isListen;
                                if (isListen) {
                                    isSpeak = false;
                                    rayMenu.changeItemStatus(1, R.drawable.armenu_hear_pressed);
                                    currentCamera.listen();
                                } else {
                                    currentCamera.mute();
                                }
                                break;
                            case 2:
                                //摄像头对讲
                                rayMenu.resetItemStatus(ITEM_DRAWABLES);
                                isSpeak = !isSpeak;
                                if (isSpeak) {
                                    isListen = false;
                                    rayMenu.changeItemStatus(2, R.drawable.armenu_void_pressed);
                                    currentCamera.speak();
                                } else {
                                    currentCamera.mute();
                                }
                                break;
                            case 3:
                                //摄像头全屏
                                FragmentManager fm = getActivity().getFragmentManager();
                                FragmentTransaction tx = fm.beginTransaction();
                                if (fm.findFragmentByTag("Camera") != null) {
                                    tx.remove(fm.findFragmentByTag("Camera")).commit();
                                }
                                view.findViewById(R.id.ray_menu).setVisibility(View.GONE);
                                view.findViewById(R.id.pb_loading).setVisibility(View.GONE);
                                view.findViewById(R.id.ll_banner).setVisibility(View.GONE);
                                sliderLayout.startAutoCycle();
                                deviceGridViewAdapter.notifyDataSetChanged();
                                mActivity.setupViewInLandscapeLayout();
                                break;
                            case 4:
                                //关闭摄像头
                                hideCameraView(currentCamera);
                                System.gc();
                                break;
                        }
                    }
                });
            }
        }
    }

    private void showVideoDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(mActivity.getString(R.string.record_title));
        String sec = mActivity.getString(R.string.record_unit);
        String[] types = {
                "10 " + sec,
                "15 " + sec,
                "30 " + sec,
                "60 " + sec
        };
        final int[] secs = {10, 15, 30, 60};
        builder.setItems(types, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                File dir = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES), getActivity().getPackageName());
                if (!dir.mkdirs()) {
                    Log.d("kukuri", "dir not created.");
                }
                File file = new File(dir, System.currentTimeMillis() + ".mp4");

                int time = secs[which];

                currentCamera.record(time, file.getPath(), new Camera.RecordingCallback() {
                    @Override
                    public void onRecordStart() {
                        mActivity.showToast(mActivity.getString(R.string.record_start));
                    }

                    @Override
                    public void onRecordFinished() {
                        mActivity.showToast(mActivity.getString(R.string.record_end));
                    }
                });
            }
        });
        builder.create().show();
    }

    /**
     * 关闭摄像头
     *
     * @param cameraBean
     */
    private void hideCameraView(final CameraBean cameraBean) {
        isSpeak = false;
        isListen = false;
        cameraBean.setShown(false);
        mActivity.setCurrentCamera(null);
//        cameraBean.stopShow();
//        cameraBean.disConnect();
        FragmentManager fm = getActivity().getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        if (fm.findFragmentByTag("Camera") != null) {
            tx.remove(fm.findFragmentByTag("Camera")).commit();
        }
        view.findViewById(R.id.ray_menu).setVisibility(View.GONE);
        view.findViewById(R.id.pb_loading).setVisibility(View.GONE);
        view.findViewById(R.id.ll_banner).setVisibility(View.GONE);
        sliderLayout.startAutoCycle();
        currentCamera = null;
        deviceGridViewAdapter.notifyDataSetChanged();
    }
//    private void initUi(final CameraBean cameraBean, final ProgressBar pbLoading, final RayMenu rayMenu) {
//        cameraBean.setOnStreamInfoUpdate(new Camera.OnStreamInfoUpdate() {
//            @Override
//            public void onFrameRateUpdate(String frameRate) {
//                if (cameraBean.isShown()) {
//                    System.out.println("FrameRate=" + frameRate);
//                }
//            }
//
//            @Override
//            public void onFrameResolutionUpdate(String resolution) {
//            }
//
//            @Override
//            public void onCameraConnected() {
//
//            }
//
//
//            @Override
//            public void onCameraStatus(String did, int status) {
//
//            }
//        });
//    }

    /**
     * PH报警范围输入检验
     *
     * @param strValue
     * @return
     */
    public String checkPhInput(String strValue) {
        if (TextUtils.isEmpty(strValue)) {
            return null;
        }
        double value;
        try {
            value = Double.valueOf(strValue);
        } catch (Exception e) {
            return getActivity().getString(R.string.input_need_number);
        }
        if (value < 0 || value > 14) {
            return getActivity().getString(R.string.input_need_forteen);
        } else {
            if (strValue.split("\\.").length == 2) {
                if (strValue.split("\\.")[1].length() > 2) {
                    return getActivity().getString(R.string.input_two_dot);
                }
            } else if (strValue.split("\\.").length == 1 && strValue.contains("\\.")) {
                return getActivity().getString(R.string.input_need_forteen);
            } else if (strValue.split("\\.").length > 2) {
                return getActivity().getString(R.string.input_need_forteen);
            }
        }
        return "True";
    }

    /**
     * 温度输入检验
     *
     * @param strValue
     * @return
     */
    public String checkTempInput(String strValue) {
        if (TextUtils.isEmpty(strValue)) {
            return null;
        }
        double value;
        try {
            value = Double.valueOf(strValue);
        } catch (Exception e) {
            return getActivity().getString(R.string.input_need_number);
        }
        if (value < 0 || value > 100) {
            return getActivity().getString(R.string.input_need_hundred);
        } else {
            if (strValue.split("\\.").length == 2) {
                if (strValue.split("\\.")[1].length() > 2) {
                    return getActivity().getString(R.string.input_one_dot);
                }
            } else if (strValue.split("\\.").length == 1 && strValue.contains("\\.")) {
                return getActivity().getString(R.string.input_need_hundred);
            } else if (strValue.split("\\.").length > 2) {
                return getActivity().getString(R.string.input_need_hundred);
            }
        }
        return "True";
    }

    /**
     * PH区间报警 砖家模式建议
     *
     * @param etAbove
     * @param etBelow
     */
    private void showPhHelpDialog(final EditText etAbove, final EditText etBelow) {
        final HashMap<String, String> infos = new HashMap<String, String>();
        infos.put(mActivity.getString(R.string.hongyu), "6.5-7.0");

        infos.put(mActivity.getString(R.string.longyu), "5.5-8.5");
        infos.put(mActivity.getString(R.string.huyu), "5-8.5");

        infos.put(mActivity.getString(R.string.jingli), "6-8.5");
        infos.put(mActivity.getString(R.string.dituyu), mActivity.getString(R.string.ruosuanzhongxingruojian));

//        infos.put(mActivity.getString(R.string.sheshuiyu), "7.0-8.0");
//        infos.put(mActivity.getString(R.string.honglvdengyu), "6.4-6.8");
//        infos.put(mActivity.getString(R.string.jinyu), "7.0-8.5");
//        infos.put(mActivity.getString(R.string.guaigunyu), mActivity.getString(R.string.suanxingruoshui));
//        infos.put(mActivity.getString(R.string.qianbiyu), mActivity.getString(R.string.ruosuanruanshui));
//        infos.put(mActivity.getString(R.string.hongqiyu), "6.5-6.8");
//        infos.put(mActivity.getString(R.string.xiongfuyu), mActivity.getString(R.string.ruosuanruanshui));
//        infos.put(mActivity.getString(R.string.hupiyu), "5.5-7.5");
//        infos.put(mActivity.getString(R.string.banmayu), mActivity.getString(R.string.yaoqiubuyan));
//        infos.put(mActivity.getString(R.string.lansanjiao), mActivity.getString(R.string.ruosuan));
//        infos.put(mActivity.getString(R.string.tzili), mActivity.getString(R.string.ruosuanruanshui));
//        infos.put(mActivity.getString(R.string.yinsha), mActivity.getString(R.string.yaoqiubuyan));
//        infos.put(mActivity.getString(R.string.sanjianshu), "7");
//        infos.put(mActivity.getString(R.string.qicaishenxian), mActivity.getString(R.string.ruosuanruanshui));
//        infos.put(mActivity.getString(R.string.jinboluo), "7-7.2");
//        infos.put(mActivity.getString(R.string.bolizhan), mActivity.getString(R.string.ruosuan));
//        infos.put(mActivity.getString(R.string.fanyoumaoyu), " 6.6-8.5");
//        infos.put(mActivity.getString(R.string.hongweinian), mActivity.getString(R.string.zhongxinghuoruojian));
//        infos.put(mActivity.getString(R.string.huashuyu), mActivity.getString(R.string.yaoqiubuyan));
//        infos.put(mActivity.getString(R.string.kafeishu), mActivity.getString(R.string.zhongxingruojian));
//        infos.put(mActivity.getString(R.string.ziluolanshu), mActivity.getString(R.string.zhongxingzuoyou));
//        infos.put(mActivity.getString(R.string.qingtongshu), mActivity.getString(R.string.yaoqiubuyan));
//        infos.put(mActivity.getString(R.string.huangguanbao), " 7.0-7.2");
//        infos.put(mActivity.getString(R.string.kongqueyu), " 7.2-7.4");
//        infos.put(mActivity.getString(R.string.yueguangyu), mActivity.getString(R.string.zhongxingruojian));
//        infos.put(mActivity.getString(R.string.jianyu), mActivity.getString(R.string.zhongxing));
//        infos.put(mActivity.getString(R.string.maliyu), mActivity.getString(R.string.ruojian));
//        infos.put(mActivity.getString(R.string.feizhoucichou), " 7.2-8.0");
//        infos.put(mActivity.getString(R.string.qiuzhangduanchou), " 5.0-6.0");
//        infos.put(mActivity.getString(R.string.qicaifenghuang), mActivity.getString(R.string.ruosuan));
//        infos.put(mActivity.getString(R.string.hongmogui), " 6.5-8.0");
//        infos.put(mActivity.getString(R.string.hualuohan), " 6.5-7.2");
        final ArrayList<String> list = new ArrayList<>();
        Iterator iter = infos.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            list.add(key);
        }
        final ListDialog helpInfoDialog = new ListDialog(getActivity());
        helpInfoDialog.setTitle(mActivity.getString(R.string.fragment_current_helpinfo_dialog_title));
        helpInfoDialog.setListviewAdapter(new HelpInfoAdapter(getActivity(), list, infos), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = list.get(position);
                String condition = infos.get(name);
                if (condition.contains("-")) {
                    String above = condition.split("-")[0];
                    String below = condition.split("-")[1];
                    etAbove.setText(above);
                    etBelow.setText(below);
                } else {
                    etAbove.setText("");
                    etBelow.setText("");
                }
                helpInfoDialog.dismiss();
            }
        });
        helpInfoDialog.setCanceledOnTouchOutside(true);
        helpInfoDialog.show();
    }

    @Override
    public void onDestroy() {
        System.out.println("BoxDetailCurrentFragment OnDestory");
//        if (currentCamera != null)
//            currentCamera.disConnect();
        ArrayList<String> address = aquariumBean.getCameras();
        //断开摄像头
        for (String cameraid : address) {
            CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(cameraid);
            cameraBean.disConnect();
        }

        hideMaintainModeStatus();
        super.onDestroy();
    }

    @Override
    public void onStop() {
        sliderLayout.stopAutoCycle();
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * 温度区间设置  砖家模式推荐
     *
     * @param etAbove
     * @param etBelow
     */
    private void showTempHelpDialog(final EditText etAbove, final EditText etBelow) {
        final HashMap<String, String> infos = new HashMap<String, String>();

        infos.put(mActivity.getString(R.string.hongyu), "26-30");

        infos.put(mActivity.getString(R.string.longyu), "28-30");
        infos.put(mActivity.getString(R.string.huyu), "26-33");

        infos.put(mActivity.getString(R.string.jingli), "20-25");
        infos.put(mActivity.getString(R.string.dituyu), "22-26");

        infos.put(mActivity.getString(R.string.jingli), "20-25");
//        infos.put(mActivity.getString(R.string.sheshuiyu), "25-30");
//        infos.put(mActivity.getString(R.string.honglvdengyu), "22-24");
//        infos.put(mActivity.getString(R.string.jinyu), "20-28");
//        infos.put(mActivity.getString(R.string.guaigunyu), "22-27");
//        infos.put(mActivity.getString(R.string.qianbiyu), "24-28");
//        infos.put(mActivity.getString(R.string.hongqiyu), "23-26");
//        infos.put(mActivity.getString(R.string.xiongfuyu), "26-28");
//        infos.put(mActivity.getString(R.string.hupiyu), "24-26");
//        infos.put(mActivity.getString(R.string.banmayu), "20-23");
//        infos.put(mActivity.getString(R.string.bolizhan), "20-25");
//        infos.put(mActivity.getString(R.string.fanyoumaoyu), "23-28");
//        infos.put(mActivity.getString(R.string.hongweinian), "24-26 ");
//        infos.put(mActivity.getString(R.string.huashuyu), "20-26");
//        infos.put(mActivity.getString(R.string.kafeishu), "22-26");
//        infos.put(mActivity.getString(R.string.ziluolanshu), "22-26");
//        infos.put(mActivity.getString(R.string.qingtongshu), "20-30");
//        infos.put(mActivity.getString(R.string.huangguanbao), "22-25");
//        infos.put(mActivity.getString(R.string.kongqueyu), "22-24");
//        infos.put(mActivity.getString(R.string.yueguangyu), "22-26");
//        infos.put(mActivity.getString(R.string.jianyu), "18-24");
//        infos.put(mActivity.getString(R.string.maliyu), "18-24");
//        infos.put(mActivity.getString(R.string.feizhoucichou), "23-28");
//        infos.put(mActivity.getString(R.string.qiuzhangduanchou), "25-27");
//        infos.put(mActivity.getString(R.string.qicaifenghuang), "24-27");
//        infos.put(mActivity.getString(R.string.hongmogui), "20-28");
//        infos.put(mActivity.getString(R.string.hualuohan), "26-28");
//        infos.put(mActivity.getString(R.string.jiewenyu), "22-26");
        final ArrayList<String> list = new ArrayList<>();
        Iterator iter = infos.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            list.add(key);
        }
        final ListDialog helpInfoDialog = new ListDialog(getActivity());
        helpInfoDialog.setTitle(mActivity.getString(R.string.fragment_current_helpinfo_dialog_title));
        helpInfoDialog.setListviewAdapter(new HelpInfoAdapter(getActivity(), list, infos), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = list.get(position);
                String condition = infos.get(name);
                if (condition.contains("-")) {
                    String above = condition.split("-")[0];
                    String below = condition.split("-")[1];
                    etAbove.setText(above);
                    etBelow.setText(below);
                }
                helpInfoDialog.dismiss();
            }
        });
        helpInfoDialog.setCanceledOnTouchOutside(true);
        helpInfoDialog.show();
    }

    /**
     * PH区间报警模式对话框
     *
     * @param deviceBean
     */
    private void showPhValueSetDialog(final DeviceBean deviceBean) {
        final ValueSetDialog tempValueSetDialog = new ValueSetDialog(getActivity());
        tempValueSetDialog.setTitle(mActivity.getString(R.string.fragment_current_set_ph_title));
        tempValueSetDialog.setPhValue();
        tempValueSetDialog.show();

        final EditText etAbove = (EditText) tempValueSetDialog.findViewById(R.id.et_ph_above);
        final EditText etBelow = (EditText) tempValueSetDialog.findViewById(R.id.et_ph_below);
        final CheckBox cbEnable = (CheckBox) tempValueSetDialog.findViewById(R.id.cb_enable);
        final ImageView ivHelp = (ImageView) tempValueSetDialog.findViewById(R.id.iv_help);
        ivHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开PH专家模式对话框
                showPhHelpDialog(etAbove, etBelow);
            }
        });
        final TextView tvPriority = (TextView) tempValueSetDialog.findViewById(R.id.tv_priority);
        tvPriority.setTag(1);
        if (DeviceConstant.alarmConditionBeanHashMap != null) {
            //已经设置过区间报警，则填充数据
            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
            if (alarmConditionBean != null) {
                etAbove.setText(String.valueOf(alarmConditionBean.getAboveValue()));
                etBelow.setText(String.valueOf(alarmConditionBean.getBelowValue()));
                if (alarmConditionBean.getEnable() == 1) {
                    cbEnable.setChecked(true);
                } else {
                    cbEnable.setChecked(false);
                }
                RuleBean deleteRule = null;
                for (Object object : SystemConstant.conditionRuleList) {
                    RuleBean ruleBean = (RuleBean) object;
                    if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                        deleteRule = ruleBean;
                    }
                }
                final RuleBean finalDeleteRule = deleteRule;
                tvPriority.setTag(finalDeleteRule.pns_priority);
                //清空数据按钮监听
                tempValueSetDialog.setClearButton(mActivity.getString(R.string.fragment_current_clear_set), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tempValueSetDialog.dismiss();
                        //规则删除指令
                        RuleManager.getInstance().Remove(connectionEntity, finalDeleteRule.toDeleteParams(), new RuleManager.RemoveCallBack() {
                            @Override
                            public void onRemoveResponseCallBack(int ret, String ruleid) {
                                if (ret == 0) {
                                    showToast(mActivity.getString(R.string.fragment_current_clear_set_success));
                                    DeviceConstant.alarmConditionBeanHashMap.remove(deviceBean.getAddress());
                                    mHandler.sendEmptyMessage(DATACHANGE);
                                }
                            }
                        });
                    }
                });
            } else {
                //打开PH专家模式对话框
                showPhHelpDialog(etAbove, etBelow);
            }
        } else {
            //打开PH专家模式对话框
            showPhHelpDialog(etAbove, etBelow);
        }
        tvPriority.setText(priorityStrIds[(int) tvPriority.getTag()]);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                设置优先级
                showPriorityWindow(tvPriority);
            }
        });
        tempValueSetDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tempValueSetDialog.dismiss();
            }
        });
        tempValueSetDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strAboveResult = checkPhInput(etAbove.getText().toString().trim());
                if (strAboveResult == null) {
                    showToast(mActivity.getString(R.string.input_need_number));
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    return;
                } else if (strAboveResult.equals("True")) {
                } else {
                    showToast(strAboveResult);
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    return;
                }
                String strBelowResult = checkPhInput(etBelow.getText().toString().trim());
                if (strBelowResult == null) {
                    showToast(mActivity.getString(R.string.input_need_number));
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                } else if (strBelowResult.equals("True")) {
                } else {
                    showToast(strBelowResult);
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                }
                if (Double.valueOf(etAbove.getText().toString().trim()) >= Double.valueOf(etBelow.getText().toString().trim())) {
                    showToast(mActivity.getString(R.string.start_must_below_end));
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                }
                showLoadingDialog(getActivity());
                if (DeviceConstant.alarmConditionBeanHashMap == null)
                    DeviceConstant.alarmConditionBeanHashMap = new HashMap<String, AlarmConditionBean>();
                AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                if (alarmConditionBean != null) {
                    RuleBean ruleBean = null;
                    RuleBean modifyRule = null;
                    for (Object object : SystemConstant.conditionRuleList) {
                        ruleBean = (RuleBean) object;
                        if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                            modifyRule = ruleBean;
                        }
                    }
                    //修改区间条件
                    modifyRule(modifyRule.getId(), cbEnable, deviceBean, etAbove, etBelow, tvPriority);
                } else {
                    //添加区间条件
                    addRule(cbEnable, deviceBean, etAbove, etBelow, tvPriority);
                }
                tempValueSetDialog.dismiss();
            }
        });
        tempValueSetDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                showInputMethod();
            }
        });
    }

    /**
     * 设置优先级对话框
     *
     * @param tvPriority
     */
    private void showPriorityWindow(final TextView tvPriority) {
        final PrioritySetDialog priorityDialog = new PrioritySetDialog(getActivity(), (Integer) tvPriority.getTag());
        priorityDialog.setTitle(mActivity.getString(R.string.alarm_priority_title));
        priorityDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.dismiss();
            }
        });
        priorityDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.checkChange();
            }
        });
        priorityDialog.setOnChangeListener(new PrioritySetDialog.OnChangeListener() {
            @Override
            public void onChange(int type) {
                switch (type) {
                    case 1:
                        if (checkPushStatus()) {
                            priorityDialog.dismiss();
                            tvPriority.setText(getString(priorityStrIds[type]));
                            tvPriority.setTag(type);
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 2:
                        if (checkPushStatus()) {
                            if (checkSmsStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                            } else {
                                //跳转到SMS界面
                                switchToSmsActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 3:
                        if (checkPushStatus()) {
                            if (checkTelStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                            } else {
                                //跳转到Tel界面
                                switchToTelActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                }
            }
        });
        priorityDialog.setCanceledOnTouchOutside(true);
        priorityDialog.show();
    }

    /**
     * 跳转到电话设置对话框
     */
    private void switchToTelActivity() {
        Intent intent = new Intent(getActivity(), TelPushMessageActivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 跳转到短信设置对话框
     */
    private void switchToSmsActivity() {
        Intent intent = new Intent(getActivity(), SmsPushMessageActivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 跳转到推送设置对话框
     */
    private void switchToPushActivity() {
        Intent intent = new Intent(getActivity(), PushMessageSettingAcitivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 检查电话状态
     *
     * @return
     */
    private boolean checkTelStatus() {
        if (SharedUtil.getInstance().readTelStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    /**
     * 检查短信状态
     *
     * @return
     */
    private boolean checkSmsStatus() {
        if (SharedUtil.getInstance().readSmsStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    /**
     * 检查推送状态
     *
     * @return
     */
    private boolean checkPushStatus() {
        if (SharedUtil.getInstance().readXinStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    /**
     * 温度区间报警对话框
     *
     * @param deviceBean
     */
    private void showTemperatureValueSetDialog(final DeviceBean deviceBean) {
        final ValueSetDialog tempValueSetDialog = new ValueSetDialog(getActivity());
        tempValueSetDialog.setTitle(mActivity.getString(R.string.fragment_current_set_temp_title));
        tempValueSetDialog.setTemperatureValue();
        tempValueSetDialog.show();

        final EditText etAbove = (EditText) tempValueSetDialog.findViewById(R.id.et_above);
        final EditText etBelow = (EditText) tempValueSetDialog.findViewById(R.id.et_below);
        final CheckBox cbEnable = (CheckBox) tempValueSetDialog.findViewById(R.id.cb_temp_check);
        final ImageView ivHelp = (ImageView) tempValueSetDialog.findViewById(R.id.iv_help);
        final TextView tvPriority = (TextView) tempValueSetDialog.findViewById(R.id.tv_priority);
        tvPriority.setTag(1);
        ivHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示专家提示对话框
                showTempHelpDialog(etAbove, etBelow);
            }
        });
        if (DeviceConstant.alarmConditionBeanHashMap != null) {
            //如果已存在该区间设置，读取并显示UI
            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
            if (alarmConditionBean != null) {
                etAbove.setText(String.valueOf(alarmConditionBean.getAboveValue() / 10.0));
                etBelow.setText(String.valueOf(alarmConditionBean.getBelowValue() / 10.0));
                if (alarmConditionBean.getEnable() == 1) {
                    cbEnable.setChecked(true);
                } else {
                    cbEnable.setChecked(false);
                }
                RuleBean deleteRule = null;
                for (Object object : SystemConstant.conditionRuleList) {
                    RuleBean ruleBean = (RuleBean) object;
                    if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                        deleteRule = ruleBean;
                    }
                }
                final RuleBean finalDeleteRule = deleteRule;
                tvPriority.setTag(finalDeleteRule.pns_priority);
                tempValueSetDialog.setClearButton(mActivity.getString(R.string.fragment_current_clear_set), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tempValueSetDialog.dismiss();
                        RuleManager.getInstance().Remove(connectionEntity, finalDeleteRule.toDeleteParams(), new RuleManager.RemoveCallBack() {
                            @Override
                            public void onRemoveResponseCallBack(int ret, String ruleid) {
                                if (ret == 0) {
                                    showToast(mActivity.getString(R.string.fragment_current_clear_set_success));
                                    DeviceConstant.alarmConditionBeanHashMap.remove(deviceBean.getAddress());
                                    mHandler.sendEmptyMessage(DATACHANGE);
                                }
                            }
                        });
                    }
                });
            } else {
                //显示专家提示对话框
                showTempHelpDialog(etAbove, etBelow);
            }
        } else {
            //显示专家提示对话框
            showTempHelpDialog(etAbove, etBelow);
        }
        tvPriority.setText(priorityStrIds[(int) tvPriority.getTag()]);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置优先级
                showPriorityWindow(tvPriority);
            }
        });
        tempValueSetDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tempValueSetDialog.dismiss();
            }
        });
        tempValueSetDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strAboveResult = checkTempInput(etAbove.getText().toString().trim());
                if (strAboveResult == null) {
                    showToast(mActivity.getString(R.string.input_need_number));
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    return;
                } else if (strAboveResult.equals("True")) {
                } else {
                    showToast(strAboveResult);
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    return;
                }
                String strBelowResult = checkTempInput(etBelow.getText().toString().trim());
                if (strBelowResult == null) {
                    showToast(mActivity.getString(R.string.input_need_number));
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                } else if (strBelowResult.equals("True")) {
                } else {
                    showToast(strBelowResult);
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                }
                if (Double.valueOf(etAbove.getText().toString().trim()) >= Double.valueOf(etBelow.getText().toString().trim())) {
                    showToast(mActivity.getString(R.string.start_must_below_end));
                    YoYo.with(Techniques.Shake).playOn(etAbove);
                    YoYo.with(Techniques.Shake).playOn(etBelow);
                    return;
                }
                showLoadingDialog(getActivity());
                if (DeviceConstant.alarmConditionBeanHashMap == null)
                    DeviceConstant.alarmConditionBeanHashMap = new HashMap<String, AlarmConditionBean>();
                AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                if (alarmConditionBean != null) {
                    RuleBean ruleBean = null;
                    RuleBean modifyRule = null;
                    for (Object object : SystemConstant.conditionRuleList) {
                        ruleBean = (RuleBean) object;
                        if (deviceBean.getAddress().equals(ruleBean.getUserTag())) {
                            modifyRule = ruleBean;
                        }
                    }
                    modifyRule(modifyRule.getId(), cbEnable, deviceBean, etAbove, etBelow, tvPriority);
                } else {
                    addRule(cbEnable, deviceBean, etAbove, etBelow, tvPriority);
                }
                tempValueSetDialog.dismiss();
            }
        });
        tempValueSetDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //强制显示输入法设置
                showInputMethod();
            }
        });
    }

    /**
     * 修改设备的名称
     *
     * @param deviceBean
     */
    private void showModifyDevice(final DeviceBean deviceBean) {
        final EditText etName;
        final InputDialog deviceNameModifyDialog = new InputDialog(getActivity());
        etName = (EditText) deviceNameModifyDialog.findViewById(R.id.et_name);
        etName.setText(deviceBean.getName());
        deviceNameModifyDialog.setHint(getString(R.string.title));
        deviceNameModifyDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = etName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    showToast(mActivity.getString(R.string.deviec_name_can_not_empty));
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("name", name);
                    jsonObject.put("label", name);
                    jsonObject.put("address", deviceBean.getAddress());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                showLoadingDialog(getActivity());
                //发送设备更新的指令
                DeviceManager.getInstance().Update(connectionEntity, jsonObject.toString(), new DeviceManager.UpdateCallBack() {
                    @Override
                    public void onUpdateResponseCallBack(int ret) {
                        if (ret == 0) {
                            deviceBean.setName(name);
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            mHandler.sendEmptyMessage(DATACHANGE);
                        } else {
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            showToast(mActivity.getString(R.string.device_name_modify_failed));
                        }
                    }
                });
            }
        });
        deviceNameModifyDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceNameModifyDialog.dismiss();
            }
        });
        deviceNameModifyDialog.show();
    }

    /**
     * 跳转到图表界面
     *
     * @param deviceBean
     */
    private void switchChartActivity(DeviceBean deviceBean) {
        Intent intent = new Intent(getActivity(), DeviceHistoryDataChartsActivity.class);
        intent.putExtra("device", deviceBean);
        intent.putExtra("uid", connectionEntity.getUid());
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_current, container, false);
        mActivity = (BoxDetailActivity) getActivity();
        gvDevice = (GridView) view.findViewById(R.id.gv_device);
        deviceGridViewAdapter = new DeviceGridViewAdapter(getActivity(), aquariumBean);
        deviceGridViewAdapter.setOnNormalIconClickListener(mOnNormalIconClickListener);
        deviceGridViewAdapter.setOnValueClickListener(mOnValueClickListener);
        deviceGridViewAdapter.setOnAlarmIconClickListener(mOnAlarmIconClickListener);
        deviceGridViewAdapter.setOnNameClickListener(mNameOnClickListener);
        deviceGridViewAdapter.setOnControlClickListener(mOnControlButtonClickListener);
        gvDevice.setAdapter(deviceGridViewAdapter);
        //获取新的广告条信息
        getNewBannerInfo(getActivity());
        //初始化Banner控件
        sliderLayout = (SliderLayout) view.findViewById(R.id.sliderlayout);
        //Banner信息的初始化
        for (BannerInfo bannerInfo : bannerInfoList) {
            TextSliderView textSliderView = new TextSliderView(getActivity());
            textSliderView.description(bannerInfo.getTitle())
                    .empty(R.drawable.banner_info)
                    .image(bannerInfo.getImageUrl())
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .setOnSliderClickListener(this);
            textSliderView.bundle(new Bundle());
            textSliderView.getBundle().putString("extra", bannerInfo.getLinkUrl());
            sliderLayout.addSlider(textSliderView);
        }
        sliderLayout.setPresetTransformer(SliderLayout.Transformer.Accordion);
        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
        sliderLayout.setCustomAnimation(new DescriptionAnimation());
        sliderLayout.setDuration(4000);
        sliderLayout.addOnPageChangeListener(this);
        currentCamera = mActivity.getCurrentCamera();

        showMaintainModeStatus();

        gvDevice.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
//                System.out.println("current view:" + absListView.getFirstVisiblePosition());
//                if (absListView.getFirstVisiblePosition() >= 8) {
//                    if (view.findViewById(R.id.framelayout_banner).getVisibility() != View.INVISIBLE)
//                        mHandler.sendEmptyMessage(HIDE_BANNER);
//                } else if (absListView.getFirstVisiblePosition() == 0) {
//                    if (view.findViewById(R.id.framelayout_banner).getVisibility() != View.VISIBLE)
//                        mHandler.sendEmptyMessage(SHOW_BANNER);
//                }
            }
        });

        SystemManager.getInstance().GetInfo(connectionEntity, new SystemManager.GetInfoCallBack() {
            @Override
            public void onGetInfoResponseCallBack(int ret, String version) {
                if (ret == 0) {
                    hubVersion = version;
                    if (SystemConstant.has_check_fw_version_in_current_fragment == 0) {
                        SystemConstant.has_check_fw_version_in_current_fragment = 1;
                        checkHubUpdate();
                    }
                }
            }
        });


        return view;
    }

    private String hubVersion;
    private CustomsizeDialog hubUpdate;

    private String updateurl = "http://fwupgrade.gangganghao.com.cn/download_aq_01/palals.json";

    private void checkHubUpdate() {
        JsonObjectRequest jsonUpdateRequest = new JsonObjectRequest(updateurl, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("TAG", response.toString());
                        dealResponse(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("TAG", error.getMessage(), error);
                    }
                });

        AQApplication.getInstance().mQueue.add(jsonUpdateRequest);
    }

    private void dealResponse(JSONObject response) {
        try {
            String version = response.getString("version");
            String url = response.getString("url");
            String md5 = response.getString("md5");
            int clear = 0;
            try {
                clear = response.getInt("clear");
            } catch (Exception e) {

            }

            String newVersion = version.replace("V", "");
            String[] newVersions = newVersion.split("\\.");
            int newT = Integer.valueOf(newVersions[0]);
            int newD = Integer.valueOf(newVersions[1]);
            int newU = Integer.valueOf(newVersions[2]);
            String oldVersion = hubVersion.replace("V", "");
            String[] oldVersions = oldVersion.split("\\.");
            int oldT = Integer.valueOf(oldVersions[0]);
            int oldD = Integer.valueOf(oldVersions[1]);
            int oldU = Integer.valueOf(oldVersions[2]);

//            showHubUpdateSureDialog(url, version, md5, clear);

            if (newT <= oldT) {
                if (newD <= oldD) {
                    if (newU <= oldU) {
//                        showToast(getString(R.string.this_is_newest_harmware_version));
                    } else {
                        showHubUpdateSureDialog(url, version, md5, clear);
                    }
                } else {
                    showHubUpdateSureDialog(url, version, md5, clear);
                }
            } else {
                showHubUpdateSureDialog(url, version, md5, clear);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showHubUpdateSureDialog(final String url, final String verison, final String md5, int clear) {
        if (hubUpdate == null) {
            hubUpdate = new CustomsizeDialog(getActivity());
            hubUpdate.setTitle(R.string.dialog_title_alert);
            hubUpdate.setCancelable(false);
            hubUpdate.setCanceledOnTouchOutside(false);
            hubUpdate.setContent(getString(R.string.activity_hub_setting_new_firmware_sure_to_settinng));
            hubUpdate.setNegativeButton(R.string.cancel, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hubUpdate.dismiss();
                }
            });
            hubUpdate.setPositiveButton(R.string.sure, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //控制中心设置
                    Intent intent = new Intent(getActivity(), HubSettingActivity.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    hubUpdate.dismiss();
                }
            });
        }
        if (!hubUpdate.isShowing()) {
            hubUpdate.show();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode=" + requestCode + ",resultCode=" + resultCode);
        if (requestCode == 0 && resultCode == 0x01) {
            resetCameraWifi();
        } else if (requestCode == 1 && resultCode == 0x02) {
            //修改Camera之后
            System.out.println("CAMID=" + data.getStringExtra("CAMID"));
            CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(data.getStringExtra("CAMID"));
            if (cameraBean != null) {
                if (cameraBean.isShown()) {
                    System.out.println("isShown");
                    hideCameraView(cameraBean);
                }
                System.out.println("reconnect");
                cameraBean.reconnect();
            }
        }
    }

    /**
     * 重设摄像头Wifi
     */
    private void resetCameraWifi() {
        if (currentCamera != null) {
            hideCameraView(currentCamera);
        }
    }

    /**
     * 读取Banner信息
     *
     * @param context
     */
    private void getNewBannerInfo(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("AQProject", Context.MODE_PRIVATE);
        String bannerinfo = sharedPreferences.getString("bannerInfo", null);
        JSONArray bannerArray = null;
        if (bannerinfo == null) {
            //此处表示第一次打开APP时就没连上网
            bannerinfo = BuildConfig.BANNERINFO;
        }
        try {
            bannerArray = new JSONArray(bannerinfo);
            int lenth = bannerArray.length();
            BannerInfo bannerInfo;
            for (int i = 0; i < lenth; i++) {
                JSONObject jsonObject = new JSONObject(bannerArray.get(i).toString());
                bannerInfo = new BannerInfo(jsonObject.toString());
                bannerInfoList.add(bannerInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        if (currentCamera != null) {
            currentCamera.stopShow();
            hideCameraView(currentCamera);
        }
        update();
        sliderLayout.startAutoCycle();
        super.onResume();
        if (currentCamera != null) {
            showCameraView(currentCamera);
        }
    }

    /**
     * 手动调用显示输入法对话框
     */
    private void showInputMethod() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 控制喂食对话框
     *
     * @param deviceBean
     */
    private void controlFeeder(final DeviceBean deviceBean) {
        double value = deviceBean.getSensorvalue();
        JSONObject jsonParams = new JSONObject();
        mHandler.sendEmptyMessage(LOADINGSTART);
        try {
            jsonParams.put("address", deviceBean.getAddress());
            jsonParams.put("value", 255);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //发送控制指令
        DeviceManager.getInstance().Control(connectionEntity, jsonParams.toString(), new DeviceManager.ControlCallBack() {
            @Override
            public void onControlResponseCallBack(int ret) {
                if (ret == 0) {
                    deviceBean.setSensorvalue(255);
                    mHandler.sendEmptyMessage(LOADINGSUCCESS);
                } else {
                    mHandler.sendEmptyMessage(LOADINGFAIL);
                }
            }
        });
    }

    /**
     * 修改区间报警设置的规则
     *
     * @param modifyRuleId
     * @param cbEnable
     * @param deviceBean
     * @param etAbove
     * @param etBelow
     * @param tvPriority
     */
    private void modifyRule(final String modifyRuleId, final CheckBox cbEnable, final DeviceBean deviceBean, final EditText etAbove, final EditText etBelow, TextView tvPriority) {
        final RuleBean ruleBean = new RuleBean();
        if (SystemConstant.conditionRuleList == null)
            SystemConstant.conditionRuleList = new ArrayList<>();
        for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
            RuleBean ruleBeans = SystemConstant.conditionRuleList.get(i);
            ArrayList<CommandBean> commandBeans = new ArrayList<CommandBean>();
            HashMap<String, TriggerBean> actiongs = new HashMap<String, TriggerBean>();
            if (ruleBeans.getId().equals(modifyRuleId)) {
                ruleBean.setEnabled(ruleBeans.getEnabled());
                ruleBean.setPns(ruleBeans.getPns());
                ruleBean.setRepeat_type(ruleBeans.getRepeat_type());
                commandBeans.addAll(ruleBeans.getCommands());
                ruleBean.setCommands(commandBeans);
                ruleBean.setIcon_data(ruleBeans.getIcon_data() == null ? null : new String(ruleBeans.getIcon_data()));
                ruleBean.setId(ruleBeans.getId() == null ? null : new String(ruleBeans.getId()));
                ruleBean.setPlace(ruleBeans.getPlace() == null ? null : new String(ruleBeans.getPlace()));
                ruleBean.setWeekdays(ruleBeans.getWeekdays());
                actiongs.putAll(ruleBeans.getTriggers());
                ruleBean.setTriggers(actiongs);
                ruleBean.setTitle(ruleBeans.getTitle() == null ? null : new String(ruleBeans.getTitle()));
                ruleBean.setUserTag(ruleBeans.getUserTag() == null ? null : new String(ruleBeans.getUserTag()));
                break;
            }
        }
        ruleBean.pns_priority = (int) tvPriority.getTag();
        if (cbEnable.isChecked())
            ruleBean.setEnabled(1);
        else
            ruleBean.setEnabled(0);
        final double belowValue = deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE ? Double.valueOf(etBelow.getText().toString().trim()) * 10 : Double.valueOf(etBelow.getText().toString().trim());
        final double aboveValue = deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE ? Double.valueOf(etAbove.getText().toString().trim()) * 10 : Double.valueOf(etAbove.getText().toString().trim());
        JSONArray jsonArray = new JSONArray();
        try {
            jsonArray.put(0, belowValue);
            jsonArray.put(1, aboveValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ruleBean.getTriggers().get(deviceBean.getAddress()).getValueConditionBeans().get(0).setThresholdList(jsonArray);
        //发送规则更新的指令
        RuleManager.getInstance().Update(connectionEntity, ruleBean.toParams().toString(), new RuleManager.UpdateCallBack() {
            @Override
            public void onUpdateResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    for (int i = 0; i < SystemConstant.conditionRuleList.size(); i++) {
                        RuleBean oldruleBean = SystemConstant.conditionRuleList.get(i);
                        if (modifyRuleId.equals(oldruleBean.getId())) {
                            SystemConstant.conditionRuleList.remove(i);
                            SystemConstant.conditionRuleList.add(ruleBean);
                            DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).setAboveValue(aboveValue);
                            DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).setBelowValue(belowValue);
                            DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).setEnable(cbEnable.isChecked() ? 1 : 0);
                            if (deviceBean.getSensorvalue() < DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getAboveValue() || deviceBean.getSensorvalue() > DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress()).getBelowValue()) {
                                deviceBean.setAlarm(true);
                            } else {
                                deviceBean.setAlarm(false);
                            }
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                }
            }
        });
    }

    /**
     * 添加水位规则
     *
     * @param cbEnable   勾选是否报警的CheckBox
     * @param deviceBean 水位设备
     * @param tvPriority 优先级的TextView
     */
    private void addWaterRule(final CheckBox cbEnable, final DeviceBean deviceBean, TextView tvPriority) {
        final RuleBean ruleBean = new RuleBean();
        ruleBean.setEnabled(1);
        if (cbEnable.isChecked()) {
            ruleBean.setPns("pns");
        }
        ruleBean.setTitle(deviceBean.getName() + "(" + mActivity.getString(R.string.aq_namemap_water_lever) + ")");
        ruleBean.setIcon_data("icon_data");
        ruleBean.setIcon_type("icon_type");
        ruleBean.setPlace(aquariumBean.getId());
        ruleBean.pns_priority = (int) tvPriority.getTag();
        ruleBean.setRepeat_type(0);
        ruleBean.setWeekdays(127);
        ruleBean.setUserTag(deviceBean.getAddress());
        HashMap<String, TriggerBean> triggerBeanHashMap = new HashMap<String, TriggerBean>();
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setAddress(deviceBean.getAddress());
        ArrayList<ValueConditionBean> valueConditionBeans = new ArrayList<ValueConditionBean>();
        ValueConditionBean valueConditionBean = new ValueConditionBean();
        valueConditionBean.setField("sensorvalue");
        valueConditionBean.setDuaration(0);
        valueConditionBean.setThreshold(0);
        valueConditionBean.setOp(">");
        valueConditionBeans.add(valueConditionBean);
        triggerBean.setValueConditionBeans(valueConditionBeans);
        triggerBeanHashMap.put(deviceBean.getAddress(), triggerBean);
        ruleBean.setTriggers(triggerBeanHashMap);
        ArrayList<CommandBean> commands = new ArrayList<CommandBean>();
        ruleBean.setCommands(commands);
        HashMap<Integer, JSONArray> timeLine = new HashMap<Integer, JSONArray>();
        for (int i = 0; i < 7; i++) {
            JSONArray jsonChild = new JSONArray();
            jsonChild.put(i * 24 * 60);
            jsonChild.put((i + 1) * 24 * 60 - 1);
            timeLine.put(i, jsonChild);
        }
        ruleBean.setTimeLine(timeLine);
        //发送添加规则的指令
        RuleManager.getInstance().Add(connectionEntity, ruleBean.toParams().toString(), new RuleManager.AddCallBack() {
            @Override
            public void onAddResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    ruleBean.setId(ruleid);
                    if (SystemConstant.conditionRuleList == null)
                        SystemConstant.conditionRuleList = new ArrayList<>();
                    SystemConstant.conditionRuleList.add(ruleBean);
                    AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                    if (alarmConditionBean == null) {
                        alarmConditionBean = new AlarmConditionBean();
                        alarmConditionBean.setEnable(1);
                        alarmConditionBean.setId(deviceBean.getDeviceid());
                    } else {
                    }
                    DeviceConstant.alarmConditionBeanHashMap.put(deviceBean.getAddress(), alarmConditionBean);
                    mHandler.sendEmptyMessage(DATACHANGE);
                    hideLoadingDialog();
                }
            }
        });
    }

    /**
     * 添加区间报警的规则
     *
     * @param cbEnable
     * @param deviceBean 触发区间报警的设备
     * @param etAbove    上限
     * @param etBelow    下限
     * @param tvPriority 优先级
     */
    private void addRule(final CheckBox cbEnable, final DeviceBean deviceBean, final EditText etAbove, final EditText etBelow, TextView tvPriority) {
        final RuleBean ruleBean = new RuleBean();
        if (cbEnable.isChecked())
            ruleBean.setEnabled(1);
        else
            ruleBean.setEnabled(0);
        if (cbEnable.isChecked()) {
            ruleBean.setPns("pns");
        }
        if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_PH) {
            ruleBean.setTitle(deviceBean.getName() + "(" + mActivity.getString(R.string.aq_namemap_ph) + ")");
        } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
            ruleBean.setTitle(deviceBean.getName() + "(" + mActivity.getString(R.string.aq_namemap_temperature) + ")");
        }
        ruleBean.setIcon_data("icon_data");
        ruleBean.setIcon_type("icon_type");
        ruleBean.pns_priority = (int) tvPriority.getTag();
        ruleBean.setPlace(aquariumBean.getId());
        ruleBean.setRepeat_type(0);
        ruleBean.setWeekdays(127);
        ruleBean.setUserTag(deviceBean.getAddress());
        HashMap<String, TriggerBean> triggerBeanHashMap = new HashMap<String, TriggerBean>();
        TriggerBean triggerBean = new TriggerBean();
        triggerBean.setAddress(deviceBean.getAddress());
        ArrayList<ValueConditionBean> valueConditionBeans = new ArrayList<ValueConditionBean>();
        ValueConditionBean valueConditionBean = new ValueConditionBean();
        valueConditionBean.setField("sensorvalue");
        valueConditionBean.setDuaration(0);
        final double belowValue = deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE ? Double.valueOf(etBelow.getText().toString().trim()) * 10 : Double.valueOf(etBelow.getText().toString().trim());
        final double aboveValue = deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE ? Double.valueOf(etAbove.getText().toString().trim()) * 10 : Double.valueOf(etAbove.getText().toString().trim());
        JSONArray jsonArray = new JSONArray();
        try {
            jsonArray.put(0, belowValue);
            jsonArray.put(1, aboveValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        valueConditionBean.setThresholdList(jsonArray);
        valueConditionBean.setOp("notin");
        valueConditionBeans.add(valueConditionBean);
        triggerBean.setValueConditionBeans(valueConditionBeans);
        triggerBeanHashMap.put(deviceBean.getAddress(), triggerBean);
        ruleBean.setTriggers(triggerBeanHashMap);
        ArrayList<CommandBean> commands = new ArrayList<CommandBean>();
        ruleBean.setCommands(commands);
        HashMap<Integer, JSONArray> timeLine = new HashMap<Integer, JSONArray>();
        for (int i = 0; i < 7; i++) {
            JSONArray jsonChild = new JSONArray();
            jsonChild.put(i * 24 * 60);
            jsonChild.put((i + 1) * 24 * 60 - 1);
            timeLine.put(i, jsonChild);
        }
        ruleBean.setTimeLine(timeLine);
        //发送添加规则的指令
        RuleManager.getInstance().Add(connectionEntity, ruleBean.toParams().toString(), new RuleManager.AddCallBack() {
            @Override
            public void onAddResponseCallBack(int ret, String ruleid) {
                if (ret == 0) {
                    ruleBean.setId(ruleid);
                    if (SystemConstant.conditionRuleList == null)
                        SystemConstant.conditionRuleList = new ArrayList<>();
                    SystemConstant.conditionRuleList.add(ruleBean);
                    AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                    if (alarmConditionBean == null) {
                        alarmConditionBean = new AlarmConditionBean();
                        alarmConditionBean.setId(deviceBean.getDeviceid());
                        alarmConditionBean.setEnable(ruleBean.getEnabled());
                        alarmConditionBean.setAboveValue(aboveValue);
                        alarmConditionBean.setBelowValue(belowValue);
                    } else {
                        alarmConditionBean.setAboveValue(aboveValue);
                        alarmConditionBean.setBelowValue(belowValue);
                    }
                    DeviceConstant.alarmConditionBeanHashMap.put(deviceBean.getAddress(), alarmConditionBean);
                    mHandler.sendEmptyMessage(DATACHANGE);
                    hideLoadingDialog();
                }
            }
        });
    }

    /**
     * 设置当前鱼缸
     *
     * @param aquarium
     */
    public void setAquarium(AquariumBean aquarium) {
        this.aquariumBean = aquarium;
    }

    /**
     * 更新UI
     */
    public void update() {
        deviceGridViewAdapter.refreshData(aquariumBean);
    }


    public void setConnectionEntity(ConnectionEntity connectionEntity) {
        this.connectionEntity = connectionEntity;
    }

    /**
     * banner图的点击事件
     *
     * @param slider
     */
    @Override
    public void onSliderClick(BaseSliderView slider) {
        //打开浏览器
        switchToBrowser(slider.getBundle().get("extra") + "");
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 跳转到浏览器
     *
     * @param linkUrl 链接
     */
    private void switchToBrowser(String linkUrl) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://bbs.innosmart.cn/forum.php?gid=54");
        intent.setData(content_url);
        startActivity(intent);
    }

    /**
     * 设置当前播放的摄像头
     *
     * @param currentCamera
     */
    public void setCurrentCamera(CameraBean currentCamera) {
        this.currentCamera = currentCamera;
    }

}

